package com.ssyx.payment.controller;

import com.ssyx.common.result.Result;
import com.ssyx.common.result.ResultCodeEnum;
import com.ssyx.enums.PaymentType;
import com.ssyx.payment.service.PaymentInfoService;
import com.ssyx.payment.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * ClassName:WeixinController
 * Description:
 *
 * @Author kay
 * @Create 2024/5/24 16:58
 * @Version 1.0
 */
//微信支付接口
@RestController
@RequestMapping("/api/payment/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinPayService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    //调用微信支付系统生成预付单
    @GetMapping("createJsapi/{orderNo}")
    public Result createJsapi(@PathVariable String orderNo){
        Map<String,String> map = weixinPayService.createJsapi(orderNo);
        return Result.ok(map);
    }

    //查询微信支付状态
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable("orderNo") String orderNo){
        //1.调用微信支付接口,查询订单支付状态
        Map<String, String> resultMap = weixinPayService.queryPayStatus(orderNo);

        //2.微信支付系统返回值为null,支付失败
        if(resultMap == null){
            return Result.build(null, ResultCodeEnum.PAYMENT_FAIL);
        }
        //3.如果微信支付系统返回值,判断支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            String out_trade_no = resultMap.get("out_trade_no");
            paymentInfoService.paySuccess(out_trade_no, resultMap);
            return Result.build(null,ResultCodeEnum.PAYMENT_SUCCESS);
        }

        //4.支付中,等待.
        return Result.build(null,ResultCodeEnum.PAYMENT_WAITING);
    }
}
